package cn.xiaoliu.hrm.filter;

import cn.xiaoliu.hrm.service.MyUserDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

public class SmsCodeProvider implements AuthenticationProvider {
    @Autowired
    private MyUserDetail myUserDetail;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //调用自己UserDetailService中的loadUserByUsername方法
        //因为此时此刻查询的是用户名密码的形式，但是传过来的是电话，所以要求电话就是名字
        //如果名字和电话号码是不同字段的情况，可以先通过名字查询到用户，再获取电话号码进行比对
        Object phone = authentication.getPrincipal();
        UserDetails user = myUserDetail.loadUserByUsername(phone.toString());
        if (user == null){
            throw new RuntimeException("用户不存在");
        }
        PhoneCodeAuthenticationToken token = new PhoneCodeAuthenticationToken(user.getUsername(),user.getPassword(),user.getAuthorities());
        return token;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (PhoneCodeAuthenticationToken.class
                .isAssignableFrom(authentication));
    }

    public MyUserDetail getMyUserDetail() {
        return myUserDetail;
    }

    public void setMyUserDetail(MyUserDetail myUserDetail) {
        this.myUserDetail = myUserDetail;
    }
}
